<%--
  Created by IntelliJ IDEA.
  User: Fmc
  Date: 2022/5/30
  Time: 11:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>用户展示</title>
    <link rel="stylesheet" href="static/layui-main/dist/css/layui.css">
    <script src="static/layui-main/src/layui.js"></script>
  </head>
  <body>

    <!-- 搜索框 -->
    <form class="layui-form" action="" id="searchForm">
      <div class="layui-inline">
        <label class="layui-form-label">用户编号</label>
        <div class="layui-input-inline">
          <input type="text" id="userid" name="userid"  placeholder="请输入用户编号" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-inline">
        <label class="layui-form-label">用户名</label>
        <div class="layui-input-inline">
          <input type="text" id="username" name="username"  placeholder="请输入用户名" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-inline">
        <div class="layui-input-inline">
          <button class="layui-btn" lay-submit lay-filter="formDemo" id="reserch">查询</button>
          <button type="reset" class="layui-btn layui-btn-primary" id="search_reset">重置</button>
        </div>
      </div>
    </form>

    <!-- 头部工具栏 -->
    <script type="text/html" id="toolbarDemo">
      <div class="layui-btn-container">
        <button class="layui-btn layui-btn layui-btn" lay-event="add">添加</button>
        <button class="layui-btn layui-btn-danger layui-btn" lay-event="delete">删除</button>
      </div>
    </script>

    <!-- 行内工具栏 -->
    <script type="text/html" id="barDemo">
      <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="resetPwd">更改密码</a>
      <a class="layui-btn layui-btn-xs" lay-event="more">更多 <i class="layui-icon layui-icon-down"></i></a>
      <%--<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="update">编辑</a>
      <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>--%>
    </script>

    <!-- 添加时，弹出的表单 -->
    <form class="layui-form" action="" id="addUserForm" style="display: none">
      <div class="layui-form-item">
        <label class="layui-form-label">用户名</label>
        <div class="layui-input-inline">
          <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名" class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-inline">
          <input type="text" name="password" required lay-verify="required" placeholder="请输入密码" class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">部门名称</label>
        <div class="layui-input-inline">
<%--          <input type="text" name="deptid" required lay-verify="required" placeholder="请输入部门编号" class="layui-input">--%>
          <select name="deptid" lay-verify="" id="deptMenuAdd">

          </select>
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-input-block">
          <button class="layui-btn" lay-submit lay-filter="addUser">提交</button>
          <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
      </div>
    </form>

    <!-- 查看时，弹出的表单 -->
    <form class="layui-form" action="" lay-filter="showUserFilter" id="showUserForm" style="display: none">
      <div class="layui-form-item">
        <label class="layui-form-label">用户编号</label>
        <div class="layui-input-inline">
          <input type="text" name="userid" required lay-verify="required" readonly class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">用户名</label>
        <div class="layui-input-inline">
          <input type="text" name="username" required lay-verify="required" readonly class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-inline">
          <input type="text" name="password" required lay-verify="required" readonly class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">盐值</label>
        <div class="layui-input-inline">
          <input type="text" name="salt" required lay-verify="required" readonly class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">部门名称</label>
        <div class="layui-input-inline">
          <input type="text" name="deptid" required lay-verify="required" readonly class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-input-block">
          <button type="button" class="layui-btn layui-btn-primary" lay-filter="closeShow" id="closeShowBtn">关闭</button>
        </div>
      </div>
    </form>

    <!-- 修改时，弹出的表单 -->
    <form class="layui-form" action="" lay-filter="updateUserFilter" id="updateUserForm" style="display: none">
      <div class="layui-form-item">
        <label class="layui-form-label">用户编号</label>
        <div class="layui-input-inline">
          <input type="text" name="userid" disabled required lay-verify="required" readonly class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">用户名</label>
        <div class="layui-input-inline">
          <input type="text" name="username" required lay-verify="required"  class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-inline">
          <input type="text" name="password" disabled required lay-verify="required"  class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">盐值</label>
        <div class="layui-input-inline">
          <input type="text" name="salt" disabled required lay-verify="required"  class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">部门名称</label>
        <div class="layui-input-inline">
<%--          <input type="text" name="deptid" required lay-verify="required"  class="layui-input">--%>
          <select name="deptid" lay-verify="" id="deptMenuUpdate">

          </select>
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-input-block">
          <button class="layui-btn" lay-submit lay-filter="updateUser">保存</button>
          <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
      </div>
    </form>

    <!-- 重置密码时，弹出的表单 -->
    <form class="layui-form" action="" lay-filter="resetPwdFilter" id="resetPwdForm" style="display: none">
        <div class="layui-form-item">
            <label class="layui-form-label">新密码</label>
            <div class="layui-input-inline">
                <input type="text" name="password" required lay-verify="required" placeholder="请输入新密码"  class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="resetPwdBtn">保存</button>
            </div>
        </div>
    </form>

    <!-- table表格 -->
    <%--lay-filter相当于dom元素的id，layui专用的选择器--%>
    <table id="demo" lay-filter="test"></table>

  </body>
  <script>

    layui.use(['table','form','jquery','dropdown'], function(){
      var table = layui.table;
      var form = layui.form;
      var $ = layui.jquery;
      var dropdown = layui.dropdown; //下拉菜单

      //第一个实例,渲染数据
      table.render({
        elem: '#demo'
        ,height: 500
        ,url: '${pageContext.request.contextPath}/userinfo?method=selectPageUser'//数据接口
        ,page: true//开启分页
        ,limit: 5
        ,limits:[5,10,15,20,25,30]
        ,autoSort: false//禁用前端的自动排序，开启后端的服务器排序
        ,toolbar: '#toolbarDemo'
        ,cols: [[
          //表头
          {type: 'checkbox', fixed: 'left'}
          ,{field: 'userid', title: '用户编号', width:120, sort: true, fixed: 'left'}
          ,{field: 'username', title: '用户名', width:100}
          ,{field: 'password', title: '密码', width:100}
          ,{field: 'salt', title: '盐值', width:180}
          ,{field: 'deptEntity', title: '部门名称', width: 177,
            templet: function (deptEntity){
              return deptEntity.deptEntity.dname;
            }}
          ,{fixed: 'right', title: '操作', width: 200, align:'center', toolbar: '#barDemo'}
        ]]
      });

      //触发排序事件
      table.on('sort(test)', function(obj){ //注：sort 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值 "
        console.log(obj.field); //当前排序的字段名
        console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
        console.log(this); //当前排序的 th 对象

        //尽管我们的 table 自带排序功能，但并没有请求服务端。
        //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
        table.reload('demo', {
          initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
          ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
            field: obj.field //排序字段
            ,order: obj.type //排序方式
          }
        });
      });

      //模糊查询,监听提交
      form.on('submit(formDemo)', function(data){
        table.reload('demo',{
          where: {
            userid: data.field.userid
            ,username: data.field.username
          }
          ,page: {
            curr: 1
          }
        });
        return false;
      });

      //重置按钮绑定单击事件
      $("#search_reset").click(function(){
        table.reload('demo',{
          where: {
            searchUserid: ""
            ,searchUsername: ""
          },
          page: {
            curr: 1
          }
        });
      });

      //监听头部工具栏事件
      table.on('toolbar(test)', function (obj){
        //获取选中的数据
        var checkStatus = table.checkStatus(obj.config.id);
        var data = checkStatus.data;
        console.log(data);
        switch (obj.event) {
          case 'add':
            layer.open({
              title: '添加用户'
              ,type: 1
              ,content:$('#addUserForm')
              ,area: ['500px','500px']
            });
            // 动态获取部门信息，并追加到下拉列表
            $.ajax({
              url: '${pageContext.request.contextPath}/deptinfo?method=selectDept'
              ,data: {}
              ,dataType: "json"
              ,type: "post"
              ,success: function (redatda) {
                $("#deptMenuAdd").empty();
                $("#deptMenuAdd").append("<option value='' selected disabled>请选择您所在部门编号</option>")
                $.each(redatda.data,function (index,val){
                  console.log(redatda.data);
                  $("#deptMenuAdd").append("<option value='"+val.deptid+"'>"+val.dname+"</option>")
                });
                layui.form.render("select");
              }
            });
            // 监听addUserForm表单的提交事件
            form.on('submit(addUser)',function (data){
              $.ajax({
                url: '${pageContext.request.contextPath}/userinfo?method=addUser'
                ,data: data.field
                ,dataType: "json"
                ,type: "post"
                ,success: function (redata) {
                  if (redata.code == 0) {
                    layer.msg(redata.msg);
                    layer.closeAll();//关闭对话框
                    table.reload('demo',{
                      page: {
                        curr: 1
                      }
                    });
                  } else {
                    layer.msg(redata.msg);
                  }
                }
              });
              return false;
            });
            break;

          case  'delete':
            if (data.length === 0) {
              layer.msg('请选择一行');
            } else {
              //layer.msg('删除');
              //定义一个数组，封装所有选中的id
              var ids = [];
              //循环所有选中的行
              for (let i=0;i<data.length;i++) {
                ids[i] = data[i].userid;
              }
              layer.confirm('真的删除选中行吗？',function (index){
                $.ajax({
                  url: '${pageContext.request.contextPath}/userinfo?method=delUser'
                  ,data: {userid:ids.join(",")}
                  ,dataType: "json"
                  ,type: "post"
                  ,success: function (redata) {
                    if (redata.code == 0) {
                      //关闭对话框
                      layer.closeAll();
                      //刷新表格数据
                      table.reload('demo',{
                        page: {
                          curr: 1
                        }
                      });
                    }
                    layer.msg(redata.msg);
                  }
                });
              });
            }
            break;
        }
      });

      //监听行工具事件
        // 单独版
      /*table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值
        if (layEvent === 'detail'){
          //layer.msg('查看操作');
          layer.open({
            title: '查看用户信息'
            ,type: 1
            ,content: $('#showUserForm')
            ,area: ["500px","500px"]
          });
          //回显用户信息
          form.val('showUserFilter',{
            "userid": data.userid
            ,"username": data.username
            ,"password": data.password
            ,"salt": data.salt
            ,"deptid": data.deptid
            ,"avatar": data.avatar
          });
          $("#closeShowBtn").on('click',function (redata){
            layer.closeAll();
          })
        } else if (layEvent === 'update') {
          layer.open({
            title: '修改用户信息'
            ,type: 1
            ,content: $('#updateUserForm')
            ,area: ["500px","500px"]
          });
          //回显用户信息
          form.val('updateUserFilter',{
            "userid": data.userid
            ,"username": data.username
            ,"password": data.password
            ,"salt": data.salt
            ,"deptid": data.deptid
            ,"avatar": data.avatar
          });
          //更新用户信息
          form.on('submit(updateUser)',function (data) {
            console.log("11")
            $.ajax({
              url: "${pageContext.request.contextPath}/userinfo?method=updateUser"
              ,data: data.field
              ,dataType: "json"
              ,type: "post"
              ,success: function (redata) {
                if (redata.code == 0) {
                  layer.closeAll();//关闭对话框
                  layer.msg(redata.msg);
                  table.reload('demo',{
                    page: {
                      curr: 1
                    }
                  });
                } else {
                  layer.msg(redata.msg);
                }
              }
            });
            return false;
          });
        } else if (layEvent === 'delete') {
          layer.confirm('真的删除吗？',function (index){
            $.ajax({
              url: "${pageContext.request.contextPath}/userinfo?method=delUser"
              ,data: {userid: data.userid}
              ,dataType: "json"
              ,type: "post"
              ,success: function (redata) {
                if (redata.code == 0) {
                  layer.msg(redata.msg);
                  layer.closeAll();//关闭对话框
                  table.reload('demo',{
                    page: {
                      curr: 1
                    }
                  });
                } else {
                  layer.msg(redata.msg);
                }
              }
            });
          })
        }
      });*/
        // 下拉菜单
        table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var userid = data.userid;
            console.log(userid);
            if(layEvent === 'resetPwd'){
                // 查看用户信息
                /*layer.open({
                    title: '查看用户信息'
                    ,type: 1
                    ,content: $('#showUserForm')
                    ,area: ["500px","500px"]
                });
                //回显用户信息
                form.val('showUserFilter',{
                    "userid": data.userid
                    ,"username": data.username
                    ,"password": data.password
                    ,"salt": data.salt
                    ,"deptid": data.deptid
                    ,"avatar": data.avatar
                });
                $("#closeShowBtn").on('click',function (redata){
                    layer.closeAll();
                })*/
                // 重置密码
              layer.open({
                title: '重置密码'
                ,type: 1
                ,content: $('#resetPwdForm')
                ,area: ["500px","500px"]
              });
              // 提交表单
              form.on('submit(resetPwdBtn)',function (data) {
                $.ajax({
                  url: "${pageContext.request.contextPath}/userinfo?method=resetPwd&&userid="+userid
                  ,data: data.field
                  ,dataType: "json"
                  ,type: "post"
                  ,success: function (redata) {
                    if (redata.code == 0) {
                      layer.closeAll();//关闭对话框
                      layer.msg(redata.msg);
                      table.reload('demo',{
                        page: {
                          curr: 1
                        }
                      });
                      window.location.href = "${pageContext.request.contextPath}/login.jsp";
                    } else {
                      layer.msg(redata.msg);
                    }
                  }
                });
                return false;
              });
            } else if(layEvent === 'more'){
                // 下拉菜单
                dropdown.render({
                    elem: this //触发事件的 DOM 对象
                    ,show: true //外部事件触发即显示
                    ,data: [{
                        title: '修改'
                        ,id: 'update'
                    },{
                        title: '删除'
                        ,id: 'delete'
                    }]
                    ,click: function(menudata){
                        if(menudata.id === 'delete'){
                            layer.confirm('真的删除行么', function(index){
                                obj.del(); //删除对应行（tr）的DOM结构
                                layer.close(index);
                                //向服务端发送删除指令
                                $.ajax({
                                    url: "${pageContext.request.contextPath}/userinfo?method=delUser"
                                    ,data: {userid: data.userid}
                                    ,dataType: "json"
                                    ,type: "post"
                                    ,success: function (redata) {
                                        if (redata.code == 0) {
                                            layer.msg(redata.msg);
                                            layer.closeAll();//关闭对话框
                                            table.reload('demo',{
                                                page: {
                                                    curr: 1
                                                }
                                            });
                                        } else {
                                            layer.msg(redata.msg);
                                        }
                                    }
                                });
                            });
                        } else if(menudata.id === 'update'){
                            layer.msg('编辑操作，当前行 ID:'+ data.id);
                            layer.open({
                                title: '修改用户信息'
                                ,type: 1
                                ,content: $('#updateUserForm')
                                ,area: ["500px","500px"]
                            });
                            // 回显用户信息
                            form.val('updateUserFilter',{
                                "userid": data.userid
                                ,"username": data.username
                                ,"password": data.password
                                ,"salt": data.salt
                                ,"avatar": data.avatar
                            });
                            // 动态的获取部门表信息
                            $.ajax({
                              url: '${pageContext.request.contextPath}/deptinfo?method=selectDept'
                              ,data: {}
                              ,dataType: "json"
                              ,type: "post"
                              ,success: function (redatda) {
                                $("#deptMenuUpdate").empty();
                                $.each(redatda.data,function (index,val){
                                  console.log(val.dname + "--" + data.deptEntity.dname);
                                  if (val.dname == data.deptEntity.dname){
                                    $("#deptMenuUpdate").append("<option selected value='"+val.deptid+"'>"+val.dname+"</option>");
                                  }else {
                                    $("#deptMenuUpdate").append("<option value='"+val.deptid+"'>"+val.dname+"</option>");
                                  }
                                });
                                layui.form.render("select");
                              }
                            });
                            // 更新用户信息
                            form.on('submit(updateUser)',function (data) {
                                $.ajax({
                                    url: "${pageContext.request.contextPath}/userinfo?method=updateUser"
                                    ,data: data.field
                                    ,dataType: "json"
                                    ,type: "post"
                                    ,success: function (redata) {
                                        if (redata.code == 0) {
                                            layer.closeAll();//关闭对话框
                                            table.reload('demo',{
                                                page: {
                                                    curr: 1
                                                }
                                            });
                                        <%--window.location.href = "${pageContext.request.contextPath}/login.jsp"--%>
                                        } else {
                                            layer.msg(redata.msg);
                                        }
                                    }
                                });
                                return false;
                            });
                        }
                    }
                    ,align: 'right' //右对齐弹出（v2.6.8 新增）
                    ,style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
                })
            }
        });

    });
  </script>
</html>

